package com.purplesoft.zettl.Listener;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Activities.EditItem;
import com.purplesoft.zettl.Adapters.CartListAdapter;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseViews.VwCartItems;
import com.purplesoft.zettl.DatabaseViews.VwItems;
import com.purplesoft.zettl.Utilities.CalculateTotalsCart;
import com.purplesoft.zettl.Utilities.Item;
import com.purplesoft.zettl.Utilities.SharedPrefs;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CartGestureListener extends SimpleOnGestureListener implements OnTouchListener {

	private Context context;
    private GestureDetector gDetector;
	private Cursor csVwCartItems;
	private ListView lvZettl;
	
    private int padding = 0;
    private int scroll = 0;
    private int initialX = 0;
    private int initialY = 0;
    private int currentX = 0;
    private int currentY = 0;
    private int pos, adapterPos;
    private int moveX = 0, moveY = 0;
    
    private boolean itemSwiped = false;
    
    private int displayWidth;
    private int itemCheckWidth, itemAlphaWidth = 0, itemAlpha = 255;
    private float itemAlphaWidthFactor;
    
    private Item item;
    private CartListAdapter cartListAdapter;
    
    private ImageView ivItem;
    private TextView tvAddRemoveItem, tvCategoryColor, tvItem, tvAmountMeasure, tvItemDescriptionManufacturer, tvCategory, tvPriceMeasure;
    private DatabaseExecuter dbExec;
    private SharedPrefs sharedPrefs;
    
    private final int DEFAULT_VALUE = -99;

    public CartGestureListener()
    {
        super();
    }

    public CartGestureListener(Context context, ListView lvZettl) {
        this(context, null, lvZettl);
    }

    public CartGestureListener(Context context, GestureDetector gDetector, ListView lvZettl) {

        if(gDetector == null)
            gDetector = new GestureDetector(context, this);

        this.context = context;
        this.gDetector = gDetector;
		this.lvZettl = lvZettl;
		
		dbExec = new DatabaseExecuter(context);
		sharedPrefs = new SharedPrefs(context);
        
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        displayWidth = displaymetrics.widthPixels;
        itemCheckWidth = (int) (displayWidth * 0.5);
        itemAlphaWidthFactor = (float) 255/itemCheckWidth;

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {

        return super.onSingleTapConfirmed(e);
    }

	
	@Override
	public boolean onDoubleTap(MotionEvent e) {
		return super.onDoubleTap(e);
	}

    private String getItem(int position) {
    	csVwCartItems = dbExec.queryFromVwCartItems(VwCartItems.Columns.ListID, sharedPrefs.getInt(context.getResources().getString(R.string.zettl_current_list_id), DEFAULT_VALUE));
    	cartListAdapter = new CartListAdapter(context, csVwCartItems);
		csVwCartItems = (Cursor) cartListAdapter.getItem(position);
		int ciItem = csVwCartItems.getColumnIndex(VwItems.Columns.Item);
		String item = csVwCartItems.getString(ciItem);
		return item;
	}

	public boolean onTouch(View v, MotionEvent event) {

        if ( event.getAction() == MotionEvent.ACTION_DOWN)
        {
            padding = 0;
            initialX = (int) event.getX();
            initialY = (int) event.getY();
            currentX = (int) event.getX();
            currentY = (int) event.getY();
            adapterPos = lvZettl.pointToPosition((int) event.getX(),(int) event.getY());
            int firstViewItemIndex = lvZettl.getFirstVisiblePosition();
            pos = adapterPos - firstViewItemIndex;
        }

        if ( event.getAction() == MotionEvent.ACTION_MOVE)
        {
        	currentY = (int) event.getY();
        	scroll = currentY - initialY;
            currentX = (int) event.getX();
            padding = currentX - initialX;
            
            if ((scroll > 20 || scroll < -20) && moveY == 0 && moveX == 0) {
            	moveY = 1;
            }
            if ((padding > 20 || padding < -20) && moveY == 0 && moveX == 0) {
            	moveX = 1;
            }
        }
        
        if ( event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL)
        {
            if ((padding < itemCheckWidth * -1) && itemSwiped == true) {
            	String ItemName = getItem(adapterPos);
        		DatabaseExecuter dbExec = new DatabaseExecuter(context);
        		item = dbExec.setItemAllAttributesFromCsVwCartItems(ItemName);
        		dbExec.insertIntoTblPurchase(item);
        		dbExec.deleteFromTblCart(item);
        		CalculateTotalsCart calculateTotalsCart = new CalculateTotalsCart();
        		calculateTotalsCart.calculateTotals(context);
        		csVwCartItems = dbExec.queryFromVwCartItems(VwCartItems.Columns.ListID, sharedPrefs.getInt(context.getResources().getString(R.string.zettl_current_list_id), DEFAULT_VALUE));
    			cartListAdapter = new CartListAdapter(context, csVwCartItems);
    			lvZettl.setAdapter(cartListAdapter);
            	Toast.makeText(context, "'" + ItemName + "' " + context.getResources().getString(R.string.put_back_to_list), Toast.LENGTH_SHORT).show();
            	
            } else {
            	if (moveX == 1) {
                	v =  lvZettl.getChildAt(pos);
                	tvAmountMeasure.setTextColor(Color.argb(255, 0, 0, 0));
                	tvPriceMeasure.setTextColor(Color.argb(255, 0, 0, 0));
                	tvItem.setTextColor(Color.argb(255, 0, 0, 0));
                	tvItemDescriptionManufacturer.setTextColor(Color.argb(255, 0, 0, 0));
                	tvCategory.setTextColor(Color.argb(255, 0, 0, 0));
                	ivItem.setAlpha(255);
                	tvCategoryColor.getBackground().setAlpha(255);
                	v.setBackgroundColor(Color.argb(0, 0, 210, 10));
                	v.scrollTo(0, 0);
                	tvAmountMeasure.setVisibility(View.VISIBLE);
                	tvPriceMeasure.setVisibility(View.VISIBLE);
                	tvItem.setVisibility(View.VISIBLE);
                	tvItemDescriptionManufacturer.setVisibility(View.VISIBLE);
                	tvCategory.setVisibility(View.VISIBLE);
                	ivItem.setVisibility(View.VISIBLE);
                	tvCategoryColor.setVisibility(View.VISIBLE);
                	tvAddRemoveItem.setVisibility(View.INVISIBLE);
            	}
            }
        	padding = 0;
        	initialX = 0;
        	initialY = 0;
        	currentX = 0;
        	currentY = 0;
        	moveX = 0;
        	moveY = 0;
        	itemSwiped = false;
        }

        if (moveX == 1) {
        	if (scroll > 0) {
        		event.setAction(MotionEvent.ACTION_CANCEL);
        	} else if (scroll < 0) {
        		event.setAction(MotionEvent.ACTION_CANCEL);
        	}
        	
        	v =  lvZettl.getChildAt(pos);
        	tvAmountMeasure = (TextView) v.findViewById(R.id.tvAmountMeasure);
        	tvPriceMeasure = (TextView) v.findViewById(R.id.tvPriceMeasure);
        	tvItem = (TextView) v.findViewById(R.id.tvItem);
        	tvItemDescriptionManufacturer = (TextView) v.findViewById(R.id.tvItemDescriptionManufacturer);
        	tvCategory = (TextView) v.findViewById(R.id.tvCategory);
        	ivItem = (ImageView) v.findViewById(R.id.ivItem);
        	tvCategoryColor = (TextView) v.findViewById(R.id.tvCategoryColor);
        	tvAddRemoveItem = (TextView) v.findViewById(R.id.tvAddRemoveItem);

        	if (padding < 0 ) {
        		itemAlphaWidth = (int) ((Math.abs(padding)) * itemAlphaWidthFactor);
        		itemAlpha = 255 - itemAlphaWidth;
        		
        		if (itemAlpha <= 0) {
                	tvAmountMeasure.setTextColor(Color.argb(0, 0, 0, 0));
                	tvPriceMeasure.setTextColor(Color.argb(0, 0, 0, 0));
                	tvItem.setTextColor(Color.argb(0, 0, 0, 0));
                	tvItemDescriptionManufacturer.setTextColor(Color.argb(0, 0, 0, 0));
                	tvCategory.setTextColor(Color.argb(0, 0, 0, 0));
                	ivItem.setAlpha(0);
                	tvCategoryColor.getBackground().setAlpha(0);
        		} else {
                	tvAmountMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
                	tvPriceMeasure.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
                	tvItem.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
                	tvItemDescriptionManufacturer.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
                	tvCategory.setTextColor(Color.argb(itemAlpha, 0, 0, 0));
                	ivItem.setAlpha(itemAlpha);
                	tvCategoryColor.getBackground().setAlpha(itemAlpha);
        		}
        		
        		if (itemAlphaWidth >= 255) {
        			itemAlphaWidth = 255;
        			itemSwiped = true;
        			
                	tvAmountMeasure.setVisibility(View.INVISIBLE);
                	tvPriceMeasure.setVisibility(View.INVISIBLE);
                	tvItem.setVisibility(View.INVISIBLE);
                	tvItemDescriptionManufacturer.setVisibility(View.INVISIBLE);
                	tvCategory.setVisibility(View.INVISIBLE);
                	ivItem.setVisibility(View.INVISIBLE);
                	tvCategoryColor.setVisibility(View.INVISIBLE);

                	v.scrollTo(0, 0);
                	
                	tvAddRemoveItem.setText(tvItem.getText().toString() + "\n" + context.getResources().getString(R.string.back_to_list));
                	tvAddRemoveItem.setVisibility(View.VISIBLE);
        		} else {
        			tvAddRemoveItem.setVisibility(View.INVISIBLE);
        			v.scrollTo(Math.abs(padding), 0);

        			tvAmountMeasure.setVisibility(View.VISIBLE);
        			tvPriceMeasure.setVisibility(View.VISIBLE);
        			tvItem.setVisibility(View.VISIBLE);
        			tvItemDescriptionManufacturer.setVisibility(View.VISIBLE);
        			tvCategory.setVisibility(View.VISIBLE);
        			ivItem.setVisibility(View.VISIBLE);
        			tvCategoryColor.setVisibility(View.VISIBLE);
        		}
        		v.setBackgroundColor(Color.argb(itemAlphaWidth, 255, 212, 73));
        	}
        	
        }
        
        return gDetector.onTouchEvent(event);
    }

    public GestureDetector getDetector()
    {
        return gDetector;
    }       

	public void startEditItem(String Item) {
		Intent intent = new Intent(context, EditItem.class);
		intent.putExtra("Item", Item);
		context.startActivity(intent);
	}

}
